// app.js
const Koa = require('koa');
const Router = require('koa-router');
const bodyParser = require('koa-bodyparser');
// const models = require('./models');
const userModel = require('./models/userModel');
const app = new Koa();
const router = new Router();


require('./models/db');
// 使用bodyParser中间件解析请求体
app.use(bodyParser());

// 定义路由
router.get('/', async (ctx) => {
  ctx.body = 'Welcome to Koa with Sequelize!';
});

// 查找所有用户
router.get('/users', async (ctx) => {
  const users = await userModel.findAll();
  ctx.body = users;
});
// 查找单个用户
router.get('/user/:id', async (ctx) => {
    const { id } = ctx.params;
    try {
      const user = await userModel.findByPk(id);
      if (user) {
        ctx.body = user;
      } else {
        ctx.status = 404;
        ctx.body = { error: 'User not found' };
      }
    } catch (error) {
      ctx.status = 400;
      ctx.body = { error: error.message };
    }
  });

//   创建用户
router.post('/user', async (ctx) => {
  const { name, age } = ctx.request.body;
  try {
    const user = await userModel.create({ name,age });
    ctx.body = user;
  } catch (error) {
    ctx.status = 400;
    ctx.body = { error: error.message };
  }
});

// 更新用户
router.put('/user/:id', async (ctx) => {
  const { id } = ctx.params;
  const { name,age } = ctx.request.body;
  try {
    const user = await userModel.findByPk(id);
    if (user) {
      await user.update({ name,age });
      ctx.body = user;
    } else {
      ctx.status = 404;
      ctx.body = { error: 'User not found' };
    }
  } catch (error) {
    ctx.status = 400;
    ctx.body = { error: error.message };
  }
});

// 删除用户
router.delete('/user/:id', async (ctx) => {
  const { id } = ctx.params;
  try {
    const user = await userModel.findByPk(id);
    if (user) {
      await user.destroy();
      ctx.status = 204;
    } else {
      ctx.status = 404;
      ctx.body = { error: 'User not found' };
    }
  } catch (error) {
    ctx.status = 500;
    ctx.body = { error: error.message };
  }
});

// 使用路由中间件
app.use(router.routes()).use(router.allowedMethods());

app.listen(3000, () => {
  console.log('Server is running at http://localhost:3000');
});